package com.ankiang.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by guosen on 2017/4/13.
 */

public class DBManager {
    private DBHelper helper;
    private SQLiteDatabase db;

    public DBManager(Context context) {
        helper = new DBHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    /**
     * add persons
     * @param dataList
     */
    public void update(List<KVData> dataList) {
        if(!db.isOpen()) {
            db = helper.getWritableDatabase();
        }
        db.beginTransaction();  //开始事务
        try {
            for (KVData d : dataList) {
                d.setUpdateTime(System.currentTimeMillis());
                db.execSQL("INSERT OR REPLACE INTO info (k, v, updateTime) VALUES(?, ?, ?)", new Object[]{d.getK(), d.getV(), d.getUpdateTime()});
            }
            db.setTransactionSuccessful();  //设置事务成功完成
        } finally {
            db.endTransaction();    //结束事务
        }
        //db.close();
    }

    /**
     * 更新数据
     * @param data
     */
    public void update(KVData data) {
        List<KVData> dataList = new ArrayList<>();
        dataList.add(data);
        update(dataList);
    }

    public void update(String k, String v){
        KVData data = new KVData();
        data.setK(k);
        data.setV(v);
        update(data);
    }

    public String get(KVData data){
        Cursor cr = db.rawQuery("SELECT v FROM info WHERE k=?", new String[]{data.getK()});
        String s = "";
        if (cr.moveToFirst()) {
            Log.i("DB", "not null");
            for (int i = 0; i < cr.getCount(); i++) {
                s = cr.getString(0);
                Log.i("DB", "s="+s);
                break;
            }
        }else {
            Log.i("DB", "is null");
        }
        return s;
    }

    public String get(String k){
        KVData data = new KVData();
        data.setK(k);
        return get(data);
    }



    /**
     * close database
     */
    public void closeDB() {
        db.close();
    }
}